(function () {

	var data = require("./data/sampleData"),
		_ = require("underscore");

	function InMemoryDataSource() {
		this.find = function (model, operators) {
			var result = data[model.__type];
			_.each(operators, function(value, key) {
				switch (value) {
					case "rowne":
						result = _.filter(result, function (entity) { return entity[key] == model[key]; });
						break;
					case "rozne":
						result = _.filter(result, function (entity) { return entity[key] != model[key]; });
						break;
					case "wieksze":
						result = _.filter(result, function (entity) { return entity[key] > model[key]; });
						break;
					case "mniejsze":
						result = _.filter(result, function (entity) { return entity[key] < model[key]; });
						break;
					case "zawiera":
						var regex = new RegExp(model[key], "i");
						result = _.filter(result, function (entity) { return entity[key].toString().match(regex); });
						break;
					default:
						throw "Podano nieprawidłowy operator: '" + value + "'";
				}
			});

			return result;
		};
		this.add = function (model) {
			var nextId = _.max(data[model.__type], function (o) { return o.id; }).id + 1;
			model.id = nextId;
			data[model.__type].push(model);
			return model;
		};
		this.update = function (model) {
			var arr = data[model.__type];
			for (var i = 0; i < arr.length; i++) {
				if (arr[i].id == model.id) {
					arr[i] = model;
					return model;
				}
			}
			return null;
		};
		this.remove = function (model) {
			var arr = data[model.__type];
			for (var i = 0; i < arr.length; i++) {
				if (arr[i].id == model.id) {
					arr.splice(i, 1);
					break;
				}
			}
			return null;
		};
	}

	module.exports = InMemoryDataSource;

})();